<script setup>
const props = defineProps({
  columns: {
    type: Array,
    default: () => [
      {
        label: 'ID',
        prop: 'id',
      },
      {
        label: '用户名',
        prop: 'username',
      },
      {
        label: '邮箱',
        prop: 'email',
      },
      {
        label: '操作',
        prop: 'action',
      },
    ],
  },
  data: {
    type: Array,
    default: () => [
      {
        id: 1,
        username: '张三',
        email: 'test@example.com',
      },
      {
        id: 2,
        username: '李四',
        email: "test@example.com",
      },
    ],
  },
})
const emit = defineEmits(["edit", "delete"])
</script>

<template>
  <div class="table-container">
    <table>
      <thead>
      <tr>
        <th
            v-for="(v,k) in props.columns"
            :key="k"
        >
          {{ v.label }}
        </th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(v,k) in props.data" :key="k">
        <template
            v-for="(v1,k1) in props.columns"
            :key="k1"
        >
          <td v-if="v1.prop !== 'action'">
            {{ v[v1.prop] }}
          </td>
          <td v-else class="action">
            <slot name="action">
              <button
                  class="btn-edit"
                  @click="emit('edit', v)"
              >
                编辑
              </button>
              <button
                  class="btn-delete"
                  @click="emit('delete', v)"
              >
                删除
              </button>
            </slot>
          </td>
        </template>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.table-container {
  box-sizing: border-box;
  width: 100%;
  max-width: 1200px;
  background-color: #ffffff; /* 表格背景色 */
  border: 1px solid #e4e7ed; /* 边框 */
  padding: 10px;
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 阴影 */
  overflow: hidden; /* 隐藏超出部分 */
  margin: 20px auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  border-radius: 8px;
}

th, td {
  padding: 12px 16px;
  text-align: left;
}

th {
  background-color: #f5f7fa; /* 表头背景色 */
  font-weight: bold;
  color: #333;
}

tbody tr {
  border-bottom: 1px solid #e8e8e8; /* 行间分隔线 */
}

tbody tr:hover {
  background-color: #f9f9f9; /* 悬停背景色 */
}

.btn-edit, .btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-edit {
  background-color: #409eff; /* 编辑按钮背景色 */
  color: #ffffff;
}

.btn-delete {
  background-color: #f56c6c; /* 删除按钮背景色 */
  color: #ffffff;
  margin-left: 8px;
}

.action {
  width: 150px;
  text-align: center;
}
</style>